# -*- coding: utf-8 -*-
'''
Created on 4 Mar 2011

@author: serj
'''
import logging
import re
from waveapi import robot
from waveapi import events
from waveapi import appengine_robot_runner
from robotUtil import tag

def getRobotInstance():
    from service.settings import ROBOT_NAME, ROBOT_IMAGE_URL, ROBOT_PROFILE_URL
    return robot.Robot(ROBOT_NAME,
                 image_url=ROBOT_IMAGE_URL,
                 profile_url=ROBOT_PROFILE_URL)

def onSubmit(event, wavelet):
    blip = event.blip
    blip_text = blip.text.lower()
    start = -1
    logging.info(event.__dict__)
    while True:
        start = blip_text.find('(', start + 1)
        if start == -1: break
        end = blip_text.find(')', start + 1)
        if end == -1: break
        if not tag.isValidTag(blip, start, end+1): continue
        blipRefs = blip.range(start, end+1)
        locale = 'en'
        replace_str = ''
        if blip_text[start:start+len(u'(экспорт')] == u'(экспорт':
            locale = 'ru'
            replace_str = u'(экспорт)'
        else:
            replace_str = '(export)'
        blipRefs.replace(replace_str)
        link = tag.generateLink(blip, start, locale=locale)
        blipRefs = blip.range(start, start + len(replace_str))
        hash_str = tag.getParameterFromLink(link, 'hash')
        blipRefs.annotate('link/manual', link)
        tag.markTag(blipRefs)
#        for child in blip.child_blips:
#            logging.info(child.blip_id)
#            tag.addIncludeLink(child, hash_str, process_childs=True)
#        for thread in blip.inline_reply_threads:
        for child in blip.child_blips:
            tag.addIncludeLink(child, hash_str, process_childs=True, locale=locale)

def onBlipCreated(event, wavelet):
    try:
        link = tag.findIncludeLink(event.new_blip, '')
        if link: return
    except:
        pass
    current_blip = event.new_blip
    while current_blip.parent_blip:
        logging.info(current_blip.blip_id)
        current_blip = current_blip.parent_blip
        try:
            locale = tag.findExportLink(current_blip)
            if locale: break
        except:
            pass
    if locale:
        tag.addIncludeLink(event.new_blip, '', locale=locale)
    
if __name__ == '__main__':
    exportbot = getRobotInstance()
    exportbot.register_handler(events.BlipSubmitted, onSubmit, events.Context.ALL)
    exportbot.register_handler(events.WaveletBlipCreated, onBlipCreated, events.Context.ALL)
    appengine_robot_runner.run(exportbot)
